<?php

namespace App\Http\Services;

use App\Http\Model\UserTags;
use Illuminate\Support\Facades\Redis;

/**
 * 用户标签
 */
class UserTagServices extends CommonServices
{
    /**
     * 用户自己的标签
     *
     * @var string
     */
    private $userSelfTagCacheKey = 'TAGS:USER:SELF:';//TAGS:USER:SELF:{用户id}


    /**
     * 根据标签id获取标签名
     *
     * @param array $tagIds
     * @return array
     */
    public function getTagNames(array $tagIds): array
    {
        if (!$tagIds) {
            return [];
        }

        $tagNames = [];
        $tags = UserTags::query()->select(['tag_id', 'name'])->whereIn('tag_id', $tagIds)->get()->keyBy('tag_id')->toArray();
        foreach ($tagIds as $tagId) {
            $tagName = $tags[$tagId]['name'] ?? '';
            if ($tagName) {
                $tagNames[$tagId] = $tagName;
            }
        }

        return $tagNames;
    }

    /**
     * Created at 2021/10/18 10:26
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $userId
     * @return string
     */
    private function getUserSelfTagCacheKey(int $userId): string
    {
        return $this->userSelfTagCacheKey . $userId;
    }

    /**
     * 获取用户自己的标签
     *
     * Created at 2021/10/18 10:24
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $userId
     * @param array $tagIds
     * @return array
     */
    public function getUserTagNamesFromCache(int $userId, array $tagIds): array
    {
        $cacheKey = $this->getUserSelfTagCacheKey($userId);
        $cache = Redis::GET($cacheKey);
        if ($cache) {
            return json_decode($cache, true);
        }

        $tagNames = $this->getTagNames($tagIds);
        $result = [];
        if ($tagNames) {
            foreach ($tagNames as $tagName) {
                $result[] = ['name' => $tagName];
            }
        }

        Redis::SET($cacheKey, json_encode($result));
        Redis::EXPIRE($cacheKey, 10 * 60 + rand(1, 60));//缓存10分钟
        return $result;
    }

    /**
     * 删除缓存
     *
     * Created at 2021/10/18 10:27
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $userId
     * @return bool
     */
    public function deleteUserSelfTagCache(int $userId): bool
    {
        Redis::DEL($this->getUserSelfTagCacheKey($userId));
        return true;
    }
}